package com.fwj.core.common.annotation;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fwj.core.common.common.LogUtils;
import com.fwj.core.common.model.DataBuriedPointLogBean;
import com.fwj.user.entity.user.UserBaseInfo;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.annotation.*;
import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.sql.Timestamp;
import java.util.List;

/**
 * @Author: fwj
 * @Data: 2022/4/16 17:08
 * @Version 1.0
 * @Description:    数据埋点日志注解，标记此注解的类，所有请求都会被记录到日志 DataBuriedPoint.log 中
 */

@Documented
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD,ElementType.FIELD,ElementType.PARAMETER,ElementType.TYPE,ElementType.PACKAGE})
public @interface DataBuriedPointLog {

    @Component
    @Aspect
    class DataBuriedPointLogHandle {

        //添加日志工厂
        private static final Logger LOGGER = LoggerFactory.getLogger(DataBuriedPointLog.class);

        @Pointcut(value = "execution(public * com.fwj..web..*.*(..))")
        private void globalPoint(){

        }

        @Around("globalPoint()")
        public Object globalAround(ProceedingJoinPoint point) throws Throwable {
            // 全局获取 request
            HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
            Object[] args = point.getArgs();
            StringBuilder sb = new StringBuilder();
            for (Object o : args){
                if (o instanceof JSONObject){
                    sb.append(JSON.toJSONString(o));
                }
            }
            //构建日志体
            DataBuriedPointLogBean dataBuriedPointLogBean = LogUtils.buildDataBuriedPointLog(request);
            dataBuriedPointLogBean.setRequestParam(sb.toString());
            Object process =point.proceed();
//            //继续执行并获取执行结果
            dataBuriedPointLogBean.setResponse(JSON.toJSONString(process));
            dataBuriedPointLogBean.setEndTime(new Timestamp(System.currentTimeMillis()));
            LOGGER.info(dataBuriedPointLogBean.toString());
            return process;
        }

    }

}
